<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>从零实现vue3.x-响应式系统 | Pluto</title><meta name="author" content="拾壹baby"><meta name="copyright" content="拾壹baby"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="这是-从零实现 Vue3.x 系列的第三篇。 这一章节来实现 Vue3.x 的响应式系统，在此之前得先搞懂一个基础知识：Vue3.x 采用的是 es5+ 的 Proxy 的方式来生成一个代理对象，并重新定义了 getter、setter 方法，这与 Vue2.x 响应原理的区别：  初始化时 vue2.x 是利用 Object.defineProperty 来拦截对象的 getter&#x2F;s">
<meta property="og:type" content="article">
<meta property="og:title" content="从零实现vue3.x-响应式系统">
<meta property="og:url" content="http://cdn.pluto1811.com/pluto/2022/08/02/vue3-03/">
<meta property="og:site_name" content="Pluto">
<meta property="og:description" content="这是-从零实现 Vue3.x 系列的第三篇。 这一章节来实现 Vue3.x 的响应式系统，在此之前得先搞懂一个基础知识：Vue3.x 采用的是 es5+ 的 Proxy 的方式来生成一个代理对象，并重新定义了 getter、setter 方法，这与 Vue2.x 响应原理的区别：  初始化时 vue2.x 是利用 Object.defineProperty 来拦截对象的 getter&#x2F;s">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://cdn.pluto1811.com/goodsImage/1654569549756/1654569530530.jpg">
<meta property="article:published_time" content="2022-08-02T05:20:55.000Z">
<meta property="article:modified_time" content="2022-11-12T03:26:18.614Z">
<meta property="article:author" content="拾壹baby">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://cdn.pluto1811.com/goodsImage/1654569549756/1654569530530.jpg"><link rel="shortcut icon" href="/pluto/img/favicon.png"><link rel="canonical" href="http://cdn.pluto1811.com/pluto/2022/08/02/vue3-03/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/pluto/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/pluto/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '从零实现vue3.x-响应式系统',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-11-12 11:26:18'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/pluto/atom.xml" title="Pluto" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/pluto/archives/"><div class="headline">文章</div><div class="length-num">22</div></a><a href="/pluto/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/pluto/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/pluto/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/pluto/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/pluto/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/pluto/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/pluto/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('http://cdn.pluto1811.com/goodsImage/1654569549756/1654569530530.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/pluto/">Pluto</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/pluto/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/pluto/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/pluto/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/pluto/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/pluto/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">从零实现vue3.x-响应式系统</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-08-02T05:20:55.000Z" title="发表于 2022-08-02 13:20:55">2022-08-02</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-11-12T03:26:18.614Z" title="更新于 2022-11-12 11:26:18">2022-11-12</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="从零实现vue3.x-响应式系统"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>这是-从零实现 Vue3.x 系列的第三篇。</p>
<p>这一章节来实现 Vue3.x 的响应式系统，在此之前得先搞懂一个基础知识：<br>Vue3.x 采用的是 es5+ 的 Proxy 的方式来生成一个代理对象，并重新定义了 getter、setter 方法，这与 Vue2.x 响应原理的区别：</p>
<ul>
<li>初始化时 vue2.x 是利用 Object.defineProperty 来拦截对象的 getter&#x2F;setter 方法，需要遍历对象所有 key，如果对象层次较深，性能不好</li>
<li>通知更新过程需要维护大量 dep 实例和 watcher 实例，额外占用内存较多</li>
<li>无法监听到数组元素的变化，只能通过劫持重写了几个数组方法</li>
<li>动态新增，删除对象属性无法拦截，只能用特定 set&#x2F;delete API 代替</li>
<li>不支持 Map、Set 等数据结构</li>
</ul>
<h3 id="一、基于-new-Proxy-重新定义响应方法"><a href="#一、基于-new-Proxy-重新定义响应方法" class="headerlink" title="一、基于 new Proxy 重新定义响应方法"></a>一、基于 new Proxy 重新定义响应方法</h3><p>在 packages 目录下新建 reactivity 目录</p>
<pre class="line-numbers language-text" data-language="text"><code class="language-text">|-packages                    -- 模块集合
    |--reactivity                  -- vue的响应式模块
        |--src
            |--index.ts                           -- reactivity模块入口文件
            |--reactive.ts                        -- 响应式模块
            |--baseHandler.ts                     -- get/set方法单独抽离出来
            |--reactiveFlags.ts                     -- 枚举值<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"><span class="token comment">// index.ts</span>
<span class="token keyword">import</span> <span class="token punctuation">&#123;</span> reactive <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">"./reactive"</span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token punctuation">&#123;</span> reactive <span class="token punctuation">&#125;</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"><span class="token comment">// reactive.ts</span>
<span class="token keyword">import</span> <span class="token punctuation">&#123;</span> <span class="token constant">REACTIVE_FLAGS</span> <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">"./reactiveFlags"</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">&#123;</span> mutaleBaseHandler <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">"./baseHandler"</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">&#123;</span> isObject <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">"@mini-vue/shared"</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> proxyMap <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">WeakMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">export</span> <span class="token keyword">const</span> <span class="token function-variable function">isReactive</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token parameter">value</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">return</span> <span class="token operator">!</span><span class="token operator">!</span><span class="token punctuation">(</span>value <span class="token operator">&amp;&amp;</span> value<span class="token punctuation">[</span><span class="token constant">REACTIVE_FLAGS</span><span class="token punctuation">.</span><span class="token constant">IS_REACTIVE</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">;</span>

<span class="token keyword">export</span> <span class="token keyword">const</span> <span class="token function-variable function">reactive</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token parameter">obj</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">isObject</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
  <span class="token comment">/*
同一个object
const obj = &#123; a: "1" &#125;;
const a = vueReactivity.reactive(obj);
const b = vueReactivity.reactive(obj);
console.log(a === b);
*/</span>
  <span class="token keyword">const</span> existProxy <span class="token operator">=</span> proxyMap<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>existProxy<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span> existProxy<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
  <span class="token comment">/*
如果一个对象已经被proxy代理过了，则直接返回
const obj = &#123; a: "1" &#125;;
const a = vueReactivity.reactive(obj);
const b = vueReactivity.reactive(a);
console.log(a === b);
*/</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>obj<span class="token punctuation">[</span><span class="token constant">REACTIVE_FLAGS</span><span class="token punctuation">.</span><span class="token constant">IS_REACTIVE</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span> obj<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
  <span class="token keyword">const</span> proxy <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Proxy</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span> mutaleBaseHandler<span class="token punctuation">)</span><span class="token punctuation">;</span>
  proxyMap<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span> proxy<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> proxy<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="二、建立-baseHandler-ts-文件，抽离-proxy-中-get、set-方法"><a href="#二、建立-baseHandler-ts-文件，抽离-proxy-中-get、set-方法" class="headerlink" title="二、建立 baseHandler.ts 文件，抽离 proxy 中 get、set 方法"></a>二、建立 baseHandler.ts 文件，抽离 proxy 中 get、set 方法</h3><pre class="line-numbers language-javascript" data-language="javascript"><code class="language-javascript"><span class="token comment">// baseHandler.ts</span>
<span class="token keyword">import</span> <span class="token punctuation">&#123;</span> <span class="token constant">REACTIVE_FLAGS</span> <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">"./reactiveFlags"</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">&#123;</span> track<span class="token punctuation">,</span> trigger <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">"./effect"</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">&#123;</span> isObject <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">"@mini-vue/shared"</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">&#123;</span> reactive <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">"./reactive"</span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token keyword">const</span> mutaleBaseHandler <span class="token operator">=</span> <span class="token punctuation">&#123;</span>
  <span class="token function">get</span><span class="token punctuation">(</span>target<span class="token punctuation">,</span> key<span class="token punctuation">,</span> receiver<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 当一个对象已经被proxy代理过了，那么再次读取REACTIVE_FLAGS.IS_REACTIVE属性时，会触发get方法，由此返回true</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>key <span class="token operator">===</span> <span class="token constant">REACTIVE_FLAGS</span><span class="token punctuation">.</span><span class="token constant">IS_REACTIVE</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 依赖收集</span>
    <span class="token function">track</span><span class="token punctuation">(</span>target<span class="token punctuation">,</span> <span class="token string">"get"</span><span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// 解决 this 的指向问题</span>
    <span class="token keyword">const</span> result <span class="token operator">=</span> Reflect<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>target<span class="token punctuation">,</span> key<span class="token punctuation">,</span> receiver<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">isObject</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">return</span> <span class="token function">reactive</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 深度代理，取值的时候才代理，性能好</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">return</span> result<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
  <span class="token function">set</span><span class="token punctuation">(</span>target<span class="token punctuation">,</span> key<span class="token punctuation">,</span> newValue<span class="token punctuation">,</span> receiver<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">const</span> oldValue <span class="token operator">=</span> target<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token keyword">const</span> result <span class="token operator">=</span> Reflect<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>target<span class="token punctuation">,</span> key<span class="token punctuation">,</span> newValue<span class="token punctuation">,</span> receiver<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span>oldValue <span class="token operator">!==</span> newValue<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token comment">// 触发更新</span>
      <span class="token function">trigger</span><span class="token punctuation">(</span>target<span class="token punctuation">,</span> <span class="token string">"set"</span><span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">return</span> result<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="三、建立-effect-ts-文件，当触发-set-时需要重新执行的函数"><a href="#三、建立-effect-ts-文件，当触发-set-时需要重新执行的函数" class="headerlink" title="三、建立 effect.ts 文件，当触发 set 时需要重新执行的函数"></a>三、建立 effect.ts 文件，当触发 set 时需要重新执行的函数</h3><pre class="line-numbers language-none"><code class="language-none">&#x2F;&#x2F; effect.ts

export let activeEffect &#x3D; undefined;

const cleanupEffect &#x3D; (context) &#x3D;&gt; &#123;
  for (let index &#x3D; 0; index &lt; context.deps.length; index++) &#123;
    const element &#x3D; context.deps[index];
    element.delete(context);
  &#125;
  context.deps.length &#x3D; 0;
&#125;;

export class ReactiveEffect &#123;
  public parent &#x3D; null;

  &#x2F;&#x2F; 储存effect对应的依赖 方便effect卸载时 删除对应的依赖
  public deps &#x3D; [];

  &#x2F;&#x2F; 标记当前effect是否被激活 只有在激活状态 才会有依赖收集
  public active &#x3D; true;

  constructor(public fn, public scheduler) &#123;&#125;

  run() &#123;
    if (!this.active) &#123;
      &#x2F;&#x2F; 未激活 只需要执行fn即可
      return this.fn();
    &#125;
    try &#123;
      &#x2F;*
effect嵌套时 activeEffect 与属性对应关系会错乱
比如：
effect(()&#x3D;&gt;&#123; effect1
    state.name name -&gt; effect1
    effect(()&#x3D;&gt;&#123; effect2
        state.age  age -&gt; effect2
    &#125;)
    state.address address -&gt; undefined ( finally 执行的结果 )
&#125;)
*&#x2F;
      this.parent &#x3D; activeEffect;
      activeEffect &#x3D; this;
      cleanupEffect(this);
      return this.fn();
    &#125; finally &#123;
      activeEffect &#x3D; this.parent;
      this.parent &#x3D; null;
    &#125;
  &#125;

  stop() &#123;
    this.active &#x3D; false;
    cleanupEffect(this);
  &#125;
&#125;

export const effect &#x3D; (fn, options: any &#x3D; &#123;&#125;) &#x3D;&gt; &#123;
  const _effect &#x3D; new ReactiveEffect(fn, options.scheduler);

  const runner &#x3D; _effect.run.bind(_effect);

  runner.effect &#x3D; _effect;

  _effect.run();

  return runner;
&#125;;

&#x2F;*
这里需要区分Map与WeakMap
WeakMap中的key只能是对象，且key为弱引用，如果key被删除了，那么垃圾回收会释放该对象所占用的内存，防止内存泄露
*&#x2F;
const targetMap &#x3D; new WeakMap();

export const trackEffects &#x3D; (dep) &#x3D;&gt; &#123;
  const shouldTrack &#x3D; dep.has(activeEffect);
  if (!shouldTrack) &#123;
    dep.add(activeEffect);
    activeEffect.deps.push(dep);
  &#125;
&#125;;

&#x2F;**
 * 此处需要注意数据结构
 * weakMap&#123;key:target,value:Map&#123;key:key,value:Set&#125;&#125;
 * @param target
 * @param type
 * @param key
 * @returns
 *&#x2F;
export const track &#x3D; (target, type, key) &#x3D;&gt; &#123;
  if (!activeEffect) return;
  let depMap &#x3D; targetMap.get(target);
  if (!depMap) &#123;
    targetMap.set(target, (depMap &#x3D; new Map()));
  &#125;
  let dep &#x3D; depMap.get(key);
  if (!dep) &#123;
    depMap.set(key, (dep &#x3D; new Set()));
  &#125;

  trackEffects(dep);
&#125;;

export const triggerEffects &#x3D; (effects) &#x3D;&gt; &#123;
  if (effects) &#123;
    &#x2F;*
逻辑分支切换时清除effect对应的依赖，对于Set数据的删除、新增、循环操作时 造成的死循环
   比如：effect(()&#x3D;&gt;flag?state.name:state.age)
*&#x2F;
    effects &#x3D; new Set(effects);
    effects.forEach((effect) &#x3D;&gt; &#123;
      &#x2F;*
 解决循环调用trigger
 * 比如：
 * effect(() &#x3D;&gt; &#123;
      state.a &#x3D; Math.random();
      document.getElementById(&quot;app&quot;).innerHTML &#x3D; state.a;
    &#125;);
*&#x2F;
      if (activeEffect !&#x3D;&#x3D; effect) &#123;
&#x2F;&#x2F; 如果用户自定义了更新函数 则执行
        if (effect.scheduler) &#123;
          effect.scheduler();
        &#125; else &#123;
          effect.run();
        &#125;
      &#125;
    &#125;);
  &#125;
&#125;;

export const trigger &#x3D; (target, type, key) &#x3D;&gt; &#123;
  const depMap &#x3D; targetMap.get(target);
  if (!depMap) return;
  let effects &#x3D; depMap.get(key);
  triggerEffects(effects);
&#125;;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://cdn.pluto1811.com/pluto">拾壹baby</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://cdn.pluto1811.com/pluto/2022/08/02/vue3-03/">http://cdn.pluto1811.com/pluto/2022/08/02/vue3-03/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://cdn.pluto1811.com/pluto" target="_blank">Pluto</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="http://cdn.pluto1811.com/goodsImage/1654569549756/1654569530530.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/pluto/2022/08/06/vue3-04/"><img class="prev-cover" src="http://cdn.pluto1811.com/goodsImage/1654586549371/1654586481783.jpg" onerror="onerror=null;src='/pluto/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">从零实现vue3.x-ref、computed、watch的实现</div></div></a></div><div class="next-post pull-right"><a href="/pluto/2022/07/20/vue3-02/"><img class="next-cover" src="http://cdn.pluto1811.com/goodsImage/1654495791805/1654495762606.jpg" onerror="onerror=null;src='/pluto/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">从零实现Vue3.x-项目搭建</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/pluto/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">拾壹baby</div><div class="author-info__description">个人博客</div></div><div class="card-info-data site-data is-center"><a href="/pluto/archives/"><div class="headline">文章</div><div class="length-num">22</div></a><a href="/pluto/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/pluto/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%9F%BA%E4%BA%8E-new-Proxy-%E9%87%8D%E6%96%B0%E5%AE%9A%E4%B9%89%E5%93%8D%E5%BA%94%E6%96%B9%E6%B3%95"><span class="toc-number">1.</span> <span class="toc-text">一、基于 new Proxy 重新定义响应方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E5%BB%BA%E7%AB%8B-baseHandler-ts-%E6%96%87%E4%BB%B6%EF%BC%8C%E6%8A%BD%E7%A6%BB-proxy-%E4%B8%AD-get%E3%80%81set-%E6%96%B9%E6%B3%95"><span class="toc-number">2.</span> <span class="toc-text">二、建立 baseHandler.ts 文件，抽离 proxy 中 get、set 方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E5%BB%BA%E7%AB%8B-effect-ts-%E6%96%87%E4%BB%B6%EF%BC%8C%E5%BD%93%E8%A7%A6%E5%8F%91-set-%E6%97%B6%E9%9C%80%E8%A6%81%E9%87%8D%E6%96%B0%E6%89%A7%E8%A1%8C%E7%9A%84%E5%87%BD%E6%95%B0"><span class="toc-number">3.</span> <span class="toc-text">三、建立 effect.ts 文件，当触发 set 时需要重新执行的函数</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/pluto/2022/10/25/me2022-10/" title="嗯，这两三年...2022年中总结"><img src="http://cdn.pluto1811.com/goodsImage/1650448154299/1650448126499.jpg" onerror="this.onerror=null;this.src='/pluto/img/404.jpg'" alt="嗯，这两三年...2022年中总结"/></a><div class="content"><a class="title" href="/pluto/2022/10/25/me2022-10/" title="嗯，这两三年...2022年中总结">嗯，这两三年...2022年中总结</a><time datetime="2022-10-25T05:20:55.000Z" title="发表于 2022-10-25 13:20:55">2022-10-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/pluto/2022/10/25/promise/" title="Promise里的代码为什么比setTimeout先执行？"><img src="http://cdn.pluto1811.com/goodsImage/1615188358809/376997778.jpg" onerror="this.onerror=null;this.src='/pluto/img/404.jpg'" alt="Promise里的代码为什么比setTimeout先执行？"/></a><div class="content"><a class="title" href="/pluto/2022/10/25/promise/" title="Promise里的代码为什么比setTimeout先执行？">Promise里的代码为什么比setTimeout先执行？</a><time datetime="2022-10-25T05:20:55.000Z" title="发表于 2022-10-25 13:20:55">2022-10-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/pluto/2022/10/23/jsobject/" title="JavaScript对象：啥？对象还有分类？"><img src="http://cdn.pluto1811.com/goodsImage/1615184906664/374751567.jpg" onerror="this.onerror=null;this.src='/pluto/img/404.jpg'" alt="JavaScript对象：啥？对象还有分类？"/></a><div class="content"><a class="title" href="/pluto/2022/10/23/jsobject/" title="JavaScript对象：啥？对象还有分类？">JavaScript对象：啥？对象还有分类？</a><time datetime="2022-10-23T05:20:55.000Z" title="发表于 2022-10-23 13:20:55">2022-10-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/pluto/2022/10/19/hexo-ci/" title="【超实用】完美实现基于hexo的博客网站自动化部署"><img src="http://cdn.pluto1811.com/20221020140348.png" onerror="this.onerror=null;this.src='/pluto/img/404.jpg'" alt="【超实用】完美实现基于hexo的博客网站自动化部署"/></a><div class="content"><a class="title" href="/pluto/2022/10/19/hexo-ci/" title="【超实用】完美实现基于hexo的博客网站自动化部署">【超实用】完美实现基于hexo的博客网站自动化部署</a><time datetime="2022-10-19T06:20:58.000Z" title="发表于 2022-10-19 14:20:58">2022-10-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/pluto/2022/10/16/jstyping/" title="JavaScript类型，有可能你不知道这些细节"><img src="http://cdn.pluto1811.com/20221020140348.png" onerror="this.onerror=null;this.src='/pluto/img/404.jpg'" alt="JavaScript类型，有可能你不知道这些细节"/></a><div class="content"><a class="title" href="/pluto/2022/10/16/jstyping/" title="JavaScript类型，有可能你不知道这些细节">JavaScript类型，有可能你不知道这些细节</a><time datetime="2022-10-16T05:20:55.000Z" title="发表于 2022-10-16 13:20:55">2022-10-16</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By 拾壹baby</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/pluto/js/utils.js"></script><script src="/pluto/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>